import moment from "moment";
import { dataSource } from "../../db/typeorm";
import { UserContainer, User, UserRole } from "../../entity/user";
import { formatPage, formatPageFileterData } from "../../utils/pages";
import { UserModel } from "./type";

// 查询用户分页列表
export async function userPage(
  query: { [key: string]: any } & { pageIndex: number; pageSize: number },
) {
  const { pageIndex, pageSize } = formatPage(query);
  const queryData = formatPageFileterData(query, [
    "status",
    "user_name",
    "user_nick",
  ]);

  let querySql = dataSource.getRepository(User).createQueryBuilder();

  // 模糊查询
  for (const key in queryData) {
    if (Object.prototype.hasOwnProperty.call(queryData, key)) {
      if (["user_name", "user_nick"].includes(key)) {
        querySql = querySql.andWhere(`${key} LIKE :${key}`, {
          [`${key}`]: `%${queryData[key]}%`,
        });
      } else {
        querySql = querySql.andWhere(`${key} = :${key}`, {
          [`${key}`]: queryData[key],
        });
      }
    }
  }

  querySql = querySql
    .orderBy("create_time", "DESC")
    .take(pageSize)
    .skip((pageIndex - 1) * pageSize)
    .andWhere("user_id != :id", { id: 1 });

  const records = await querySql.getMany(); // 获取查询结果
  const total = await querySql.getCount(); // 获取符合条件的数据总数

  return { total, records };
}

// 添加用户
export async function userAdd(user: UserContainer) {
  return await dataSource.transaction(async (transactionalEntityManager) => {
    // 创建用户
    const response = await transactionalEntityManager
      .createQueryBuilder()
      .insert()
      .into(User)
      .values(user)
      .execute();

    // 创建角色权限
    if (user.roles) {
      let roleArr: UserRole = user.roles.split(",").map((item) => ({
        role_id: item,
        user_id: response.raw.insertId,
      })) as unknown as UserRole;

      await transactionalEntityManager
        .createQueryBuilder()
        .insert()
        .into(UserRole)
        .values(roleArr)
        .execute();
    }
  });
}

// 修改用户
export async function userUpdate(user: UserContainer) {
  return await dataSource.transaction(async (transactionalEntityManager) => {
    let roles = user.roles;
    delete user.roles;
    // 修改用户
    await transactionalEntityManager
      .createQueryBuilder()
      .insert()
      .update(User)
      .set(user)
      .where("user_id = :id", { id: user.user_id })
      .execute();
    // 删除角色权限
    await transactionalEntityManager
      .createQueryBuilder()
      .delete()
      .from("user_role")
      .where("user_id = :id", { id: user.user_id })
      .execute();

    // 添加新的角色权限
    if (roles) {
      let roleArr: UserRole = roles.split(",").map((item) => ({
        role_id: item,
        user_id: user.user_id,
      })) as unknown as UserRole;

      await transactionalEntityManager
        .createQueryBuilder()
        .insert()
        .into(UserRole)
        .values(roleArr)
        .execute();
    }
  });
}

// 根据账号查询单个用户
export async function userFindOne(data: any) {
  return await dataSource.getRepository(User).findOneBy(data);
}

// 根据账号查询单个用户
export async function userFindOneByUserId(user_id: string | number) {
  return await dataSource
    .getRepository(User)
    .findOneBy({ user_id: Number(user_id) });
}

// 根据用户id查询用户下的所有角色码
export async function userRoleFindOne(user_id: number) {
  const userRoles = await dataSource.getRepository(UserRole).find({
    relations: {
      role: true,
    },
  });

  let promises: string[] = [];
  let menuIds: string[] = []; // 备份该用户所属的角色
  userRoles.forEach((role) => {
    if (role.user_id === user_id && role.role && role.role.role_code) {
      promises.push(...role.role.role_code.split(","));
      // 菜单收集
      if (role.role.menu_ids) {
        menuIds.push(...role.role.menu_ids.split(","));
      }
    }
  });
  const roles = (userRoles || []).map((item) => item.role);
  menuIds = Array.from(new Set(menuIds));
  promises = Array.from(new Set(promises));
  return { promises, menuIds, roles };
}

// 根据用户id查询用户下的所有角色
export async function getUserRoleByUserId(user_id: number): Promise<number[]> {
  const userRoles = await dataSource
    .getRepository(UserRole)
    .createQueryBuilder()
    .where({ user_id: user_id })
    .getMany();
  return userRoles.map((item) => item.role_id);
}

// 根据ids [] 删除用户
export async function userDelByUserIds(ids: string[]) {
  await dataSource.getRepository(User).delete(ids);
}

// 修改用户的登录时间
export async function userUpdateLoginTime(user_id: number | string) {
  await dataSource
    .createQueryBuilder()
    .update(User, {
      login_time: moment(new Date()).format("YYYY-MM-DD HH:mm:ss"),
    })
    .where("user_id = :id", { id: user_id })
    .execute();
}
